const fs = require('fs');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

// 定义入口路径
const entryPath = ['./src/lay/modules'];
const exclude = ['jquery.js','layer.js','zepto.js'];

// 遍历路径下多文件入口
var mkEntriesMap = function (entryPath) {
    if (typeof (entryPath) == 'string') { // 若 entryPath 为字符串，则直接遍历此目录
        var path_map = fs.readdirSync(entryPath).map(function (filename) {
            return filename + '::./' + path.join(entryPath, filename);
        });
    } else if (typeof (entryPath) == 'object') { // 若 entryPath 为数组，则进行两级遍历
        var path_map = entryPath.map(function (entry) {
            return fs.readdirSync(entry).map(function (filename) {

                return filename + '::./' + path.join(entry, filename);
            });
        }).reduce(function (preArr, curArr) {
            return preArr.concat(curArr);
        }, []);
    } else {
        throw 'Type of config.entryPath is not valid.';
        return;
    }

    return path_map.reduce(function (o, file_map) {
        var file_name = file_map.split('::')[0];
        var file_path = file_map.split('::')[1];

        //   if (!/\./.test(file_name)) {
        //    o[file_name] = file_path;
        //   }
        if (!exclude.includes(file_name)) {
            o[file_name.replace(/\.js/g,'')] = file_path;
        }
        return o;
    }, {});
};

console.log(mkEntriesMap(entryPath))

// 构造对象
module.exports = {
    entry: mkEntriesMap(entryPath),
    output: {
        path: path.resolve(__dirname, 'dist/src/lay/modules'),
        filename: '[name].js'
    },
    optimization: {
        minimizer: [new UglifyJsPlugin()],
    },
    module: {
        rules: [{
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                }
            }
        }]
    }
};